import type { BOMApi } from '#/models/bom/bom';

import { requestClient } from '#/api/request';

/**
 * 分页数据响应接口
 */
export interface PageResponse<T> {
  items: T[];
  total: number;
  page?: number;
  pageSize?: number;
}

/**
 * BOM列表查询参数接口
 */
export interface BOMQueryParams {
  page?: number;
  pageSize?: number;
  bom_code?: string;
  product?: number;
  product_name?: string;
  product_sku?: string;
  bom_type?: BOMApi.BOMType;
  status?: BOMApi.BOMStatus;
  lifecycle_status?: BOMApi.LifecycleStatus;
  effective_date?: string;
  expiry_date?: string;
  is_active?: boolean;
  created_by?: string;
  create_time?: string;
  update_time?: string;
  [key: string]: any;
}

/**
 * 获取BOM列表
 * @param params - 查询参数，支持分页、过滤和排序
 * @returns 分页的BOM列表数据
 */
export const getBOMList = (
  params?: BOMQueryParams,
): Promise<PageResponse<BOMApi.BOM>> => {
  return requestClient.get('/bom/', { params });
};

/**
 * 获取单个BOM详情
 * @param bomId - BOM ID
 * @returns BOM详情
 */
export const getBOM = (bomId: number): Promise<BOMApi.BOM> => {
  return requestClient.get(`/bom/${bomId}/`);
};

/**
 * 创建BOM
 * @param data - BOM数据
 * @returns 创建成功的BOM信息
 */
export const createBOM = (data: Partial<BOMApi.BOM>): Promise<BOMApi.BOM> => {
  return requestClient.post('/bom/', data);
};

/**
 * 更新BOM
 * @param bomId - BOM ID
 * @param data - 更新的BOM信息
 * @returns 更新后的BOM信息
 */
export const updateBOM = (
  bomId: number,
  data: Partial<BOMApi.BOM>,
): Promise<BOMApi.BOM> => {
  return requestClient.put(`/bom/${bomId}/`, data);
};

/**
 * 删除BOM
 * @param bomId - BOM ID
 * @returns 删除结果
 */
export const deleteBOM = (bomId: number): Promise<any> => {
  return requestClient.delete(`/bom/${bomId}/`);
};

/**
 * 检查BOM编码唯一性
 * @param bomCode - BOM编码
 * @param excludeId - 排除的BOM ID（用于编辑时检查）
 * @returns 检查结果
 */
export const checkBOMCodeUnique = (
  bomCode: string,
  excludeId?: number,
): Promise<{ is_unique: boolean }> => {
  const params = { bom_code: bomCode };
  if (excludeId) {
    params['exclude_id'] = excludeId;
  }
  return requestClient.get('/bom/check_bom_code/', { params });
};

/**
 * 获取指定产品的所有BOM版本
 * @param productId - 产品ID
 * @returns BOM版本列表
 */
export const getProductBOMs = (productId: number): Promise<BOMApi.BOM[]> => {
  return requestClient.get(`/bom/product_boms?product_id=${productId}`);
};

/**
 * 获取产品当前有效的BOM
 * @param productId - 产品ID
 * @returns 当前有效的BOM
 */
export const getActiveBOM = (productId: number): Promise<BOMApi.BOM> => {
  return requestClient.get(`/bom/active_bom?product_id=${productId}`);
};

/**
 * 计算BOM成本
 * @param bomId - BOM ID
 * @returns 成本计算结果
 */
export const calculateBOMCost = (
  bomId: number,
): Promise<{
  labor_cost?: number;
  material_cost?: number;
  message?: string;
  overhead_cost?: number;
  total_cost: number;
}> => {
  return requestClient.post(`/bom/${bomId}/calculate-cost/`);
};

/**
 * 克隆BOM
 * @param bomId - BOM ID
 * @param data - 克隆参数
 * @returns 克隆的BOM
 */
export const cloneBOM = (
  bomId: number,
  data: {
    bom_code: string;
    bom_type: BOMApi.BOMType;
    copy_alternatives?: boolean;
    copy_components?: boolean;
    copy_documents?: boolean;
    target_product_id: number;
    version: string;
  },
): Promise<BOMApi.BOM> => {
  return requestClient.post(`/bom/${bomId}/clone/`, data);
};

/**
 * 更改BOM状态
 * @param bomId - BOM ID
 * @param data - 状态数据
 * @returns 更新结果
 */
export const changeBOMStatus = (
  bomId: number,
  data: {
    lifecycle_status: BOMApi.LifecycleStatus;
  },
): Promise<{ new_status: string }> => {
  return requestClient.patch(`/bom/${bomId}/change-status/`, data);
};

/**
 * 导入BOM数据
 * @param formData - 表单数据
 * @returns 导入结果
 */
export const importBOM = (
  formData: FormData,
): Promise<{
  error_report_url?: string;
  fail_count: number;
  message?: string;
  success_count: number;
}> => {
  return requestClient.post('/bom/import/', formData, {
    headers: {
      'Content-Type': 'multipart/form-data',
    },
  });
};

/**
 * 导出BOM数据
 * @param bomId - BOM ID
 * @returns 导出文件
 */
export const exportBOM = (bomId: number): Promise<Blob> => {
  return requestClient.get(`/bom/${bomId}/export/`, {
    responseType: 'blob',
  });
};

// ==================== 字典数据API ====================

/**
 * 获取BOM模块字典数据
 * @param dictType - 字典类型，可选，不传则返回所有BOM相关字典
 * @returns 字典数据
 */
export const getBOMDictData = (dictType?: string): Promise<{
  dict_type?: string;
  dict_types?: string[];
  data: any;
}> => {
  const params = dictType ? { dict_type: dictType } : {};
  return requestClient.get('/bom/boms/dict-data/', { params });
};

// ==================== BOM组件API ====================

/**
 * BOM组件查询参数接口
 */
export interface BOMComponentQueryParams {
  bom_id?: number;
  material?: number;
  material_name?: string;
  material_sku?: string;
  unit?: string;
  operation_code?: string;
  workstation?: string;
  preferred_supplier?: number;
  [key: string]: any;
}

/**
 * 获取BOM组件列表
 * @param params - 查询参数
 * @returns BOM组件列表
 */
export const getBOMComponents = (
  params?: BOMComponentQueryParams,
): Promise<BOMApi.BOMComponent[]> => {
  return requestClient.get('/bom/components/', { params });
};

/**
 * 获取单个BOM组件详情
 * @param componentId - 组件ID
 * @returns BOM组件详情
 */
export const getBOMComponent = (
  componentId: number,
): Promise<BOMApi.BOMComponent> => {
  return requestClient.get(`/bom/components/${componentId}/`);
};

/**
 * 添加BOM组件
 * @param data - 组件数据
 * @returns 添加的组件
 */
export const addBOMComponent = (
  data: Partial<BOMApi.BOMComponent> & { bom_id: number },
): Promise<BOMApi.BOMComponent> => {
  return requestClient.post('/bom/components/', data);
};

/**
 * 更新BOM组件
 * @param componentId - 组件ID
 * @param data - 更新的组件数据
 * @returns 更新后的组件
 */
export const updateBOMComponent = (
  componentId: number,
  data: Partial<BOMApi.BOMComponent>,
): Promise<BOMApi.BOMComponent> => {
  return requestClient.put(`/bom/components/${componentId}/`, data);
};

/**
 * 删除BOM组件
 * @param componentId - 组件ID
 * @returns 删除结果
 */
export const deleteBOMComponent = (componentId: number): Promise<any> => {
  return requestClient.delete(`/bom/components/${componentId}/`);
};

/**
 * 批量添加BOM组件
 * @param bomId - BOM ID
 * @param data - 组件数据数组
 * @returns 添加的组件
 */
export const batchAddBOMComponents = (
  bomId: number,
  data: Partial<BOMApi.BOMComponent>[],
): Promise<BOMApi.BOMComponent[]> => {
  return requestClient.post('/bom/components/batch-add/', {
    bom_id: bomId,
    components: data,
  });
};

/**
 * 批量更新BOM组件
 * @param data - 更新数据
 * @returns 更新结果
 */
export const batchUpdateBOMComponents = (data: {
  components: Array<{ id: number; quantity: number; unit_cost?: number }>;
}): Promise<BOMApi.BOMComponent[]> => {
  return requestClient.post('/bom/components/batch-update/', data);
};

// ==================== BOM版本API ====================

/**
 * BOM版本查询参数接口
 */
export interface BOMVersionQueryParams {
  bom_id?: number;
  version?: string;
  status?: string;
  is_active?: boolean;
  [key: string]: any;
}

/**
 * 获取BOM版本列表
 * @param params - 查询参数
 * @returns BOM版本列表
 */
export const getBOMVersions = (
  params?: BOMVersionQueryParams,
): Promise<BOMApi.BOMVersion[]> => {
  return requestClient.get('/bom/versions/', { params });
};

/**
 * 获取单个BOM版本详情
 * @param versionId - 版本ID
 * @returns BOM版本详情
 */
export const getBOMVersion = (
  versionId: number,
): Promise<BOMApi.BOMVersion> => {
  return requestClient.get(`/bom/versions/${versionId}/`);
};

/**
 * 创建BOM版本
 * @param data - 版本数据
 * @returns 创建的版本
 */
export const createBOMVersion = (
  data: Partial<BOMApi.BOMVersion>,
): Promise<BOMApi.BOMVersion> => {
  return requestClient.post('/bom/versions/', data);
};

/**
 * 更新BOM版本
 * @param versionId - 版本ID
 * @param data - 更新的版本数据
 * @returns 更新后的版本
 */
export const updateBOMVersion = (
  versionId: number,
  data: Partial<BOMApi.BOMVersion>,
): Promise<BOMApi.BOMVersion> => {
  return requestClient.put(`/bom/versions/${versionId}/`, data);
};

/**
 * 删除BOM版本
 * @param versionId - 版本ID
 * @returns 删除结果
 */
export const deleteBOMVersion = (versionId: number): Promise<any> => {
  return requestClient.delete(`/bom/versions/${versionId}/`);
};

/**
 * 激活BOM版本
 * @param versionId - 版本ID
 * @param data - 激活参数
 * @returns 激活结果
 */
export const activateBOMVersion = (
  versionId: number,
  data: { remark?: string },
): Promise<BOMApi.BOMVersion> => {
  return requestClient.post(`/bom/versions/${versionId}/activate/`, data);
};

// ==================== 替代物料API ====================

/**
 * 替代物料查询参数接口
 */
export interface AlternativeMaterialQueryParams {
  component_id?: number;
  alternative_material?: number;
  is_active?: boolean;
  approval_status?: string;
  [key: string]: any;
}

/**
 * 获取替代物料列表
 * @param params - 查询参数
 * @returns 替代物料列表
 */
export const getAlternativeMaterials = (
  params?: AlternativeMaterialQueryParams,
): Promise<BOMApi.AlternativeMaterial[]> => {
  return requestClient.get('/bom/alternatives/', { params });
};

/**
 * 获取单个替代物料详情
 * @param altMaterialId - 替代物料ID
 * @returns 替代物料详情
 */
export const getAlternativeMaterial = (
  altMaterialId: number,
): Promise<BOMApi.AlternativeMaterial> => {
  return requestClient.get(`/bom/alternatives/${altMaterialId}/`);
};

/**
 * 创建替代物料
 * @param data - 替代物料数据
 * @returns 创建的替代物料
 */
export const createAlternativeMaterial = (
  data: Partial<BOMApi.AlternativeMaterial>,
): Promise<BOMApi.AlternativeMaterial> => {
  return requestClient.post('/bom/alternatives/', data);
};

/**
 * 更新替代物料
 * @param altMaterialId - 替代物料ID
 * @param data - 更新的替代物料数据
 * @returns 更新后的替代物料
 */
export const updateAlternativeMaterial = (
  altMaterialId: number,
  data: Partial<BOMApi.AlternativeMaterial>,
): Promise<BOMApi.AlternativeMaterial> => {
  return requestClient.put(`/bom/alternatives/${altMaterialId}/`, data);
};

/**
 * 删除替代物料
 * @param altMaterialId - 替代物料ID
 * @returns 删除结果
 */
export const deleteAlternativeMaterial = (
  altMaterialId: number,
): Promise<any> => {
  return requestClient.delete(`/bom/alternatives/${altMaterialId}/`);
};

// ==================== BOM文档API ====================

/**
 * BOM文档查询参数接口
 */
export interface BOMDocumentQueryParams {
  bom_id?: number;
  component_id?: number;
  document_type?: string;
  document_name?: string;
  [key: string]: any;
}

/**
 * 获取BOM文档列表
 * @param params - 查询参数
 * @returns BOM文档列表
 */
export const getBOMDocuments = (
  params?: BOMDocumentQueryParams,
): Promise<BOMApi.BOMDocument[]> => {
  return requestClient.get('/bom/documents/', { params });
};

/**
 * 获取单个BOM文档详情
 * @param documentId - 文档ID
 * @returns BOM文档详情
 */
export const getBOMDocument = (
  documentId: number,
): Promise<BOMApi.BOMDocument> => {
  return requestClient.get(`/bom/documents/${documentId}/`);
};

/**
 * 上传BOM文档
 * @param data - 文档数据
 * @returns 上传的文档
 */
export const uploadBOMDocument = (
  data: FormData,
): Promise<BOMApi.BOMDocument> => {
  return requestClient.post('/bom/documents/', data, {
    headers: {
      'Content-Type': 'multipart/form-data',
    },
  });
};

/**
 * 删除BOM文档
 * @param documentId - 文档ID
 * @returns 删除结果
 */
export const deleteBOMDocument = (documentId: number): Promise<any> => {
  return requestClient.delete(`/bom/documents/${documentId}/`);
};

// ==================== 通用API ====================

/**
 * 获取产品列表
 * @returns 产品列表
 */
export const getProducts = (): Promise<any[]> => {
  return requestClient.get('/product/product/');
};

/**
 * 获取物料列表
 * @returns 物料列表
 */
export const getMaterials = (): Promise<any[]> => {
  return requestClient.get('/product/material/');
};

/**
 * 下载BOM导入模板
 * @returns 导入模板文件
 */
export const downloadBOMTemplate = (): Promise<Blob> => {
  return requestClient.get('/bom/template/', {
    responseType: 'blob',
  });
};
